#!/usr/bin/env python

"""
This example demonstrates how to use async IO with python-can.
"""

import asyncio
from typing import List

import can
from can.notifier import MessageRecipient


def print_message(msg: can.Message) -> None:
    """can 接受回调"""
    print(msg)
    """ msg
    can.Message(timestamp=1739267052.5670009, arbitration_id=0x1, is_extended_id=False, 
        is_rx=False, channel='vcan0', dlc=4, data=[0x12, 0x34, 0x56, 0x78])
    """


async def main() -> None:
    with can.Bus(channel="vcan0", interface="socketcan") as bus:
        reader = can.AsyncBufferedReader()
        logger = can.Logger("logfile.asc")

        listeners: List[MessageRecipient] = [
            print_message,  # Callback function
            reader,  # AsyncBufferedReader() listener
            logger,  # Regular Listener object
        ]
        # Create Notifier with an explicit loop to use for scheduling of callbacks
        loop = asyncio.get_running_loop()
        notifier = can.Notifier(bus, listeners, loop=loop)

        while True:
            msg = await reader.get_message()
            print("recv can:")

        # Wait for last message to arrive
        await reader.get_message()
        print("Done!")

        # Clean-up
        notifier.stop()


if __name__ == "__main__":
    asyncio.run(main())
